class CreateWordController < ApplicationController

  def create
    user_id = session[:user_id]

    if user_id == nil
      redirect_to :controller => "login", :action => "login"
    end

    @storage = EditWordStorage.new("", "", "")

    if request.post?
      @storage = EditWordStorage.new(request.params["original_word"],
                                     request.params["translations"],
                                     request.params["invalid_translations"])

      begin
        @storage.try_to_save(user_id)
        @storage = EditWordStorage.new("", "", "")
      rescue CreateWordHelper::CreationErrors => e
        flash[:notice] = e.to_s
      end
    end
  end

  def edit

    user_id = session[:user_id]

    if user_id == nil
      redirect_to :controller => "login", :action => "login"
    end

    if request.get?
      if request[:word] == nil && request[:should] == nil || request[:should] != "edit"
        redirect_to :action => create
      end

      word = Word.find_by_id(request[:word])
      if word == nil || word.user_id != session[:user_id]
        #todo redirect
        redirect_to :controller => "error", :action => "error"
      end

      @storage = EditWordStorage.from_word(word)
      @wid = word.id
    end

    if request.post?
      if request[:wid] == nil
        redirect_to :controller => "error", :action => "error"
      end
      @storage = EditWordStorage.new(request.params["original_word"],
                                     request.params["translations"],
                                     request.params["invalid_translations"])
      @storage.try_to_edit(request[:wid], user_id)
      redirect_to :controller => "main_page", :action => "main"
    end
  end
end
